//
//  MultiSelectPicker.m
//  PT
//
//  Created by yate1996 on 15/6/16.
//  Copyright (c) 2015年 jarze. All rights reserved.
//

#import "MultiSelectPicker.h"
NSString * const PTbackgroundColor = @"backgroundColor";
NSString * const PTtextColor = @"textColor";
NSString * const PTtoolbarColor = @"toolbarColor";
NSString * const PTbuttonColor = @"buttonColor";
NSString * const PTfont = @"font";
NSString * const PTvalueY = @"yValueFromTop";
NSString * const PTselectedObject = @"selectedObject";
NSString * const PTtoolbarBackgroundImage = @"toolbarBackgroundImage";
NSString * const PTtextAlignment = @"textAlignment";
NSString * const PTshowsSelectionIndicator = @"showsSelectionIndicator";

@interface MultiSelectPicker ()<UIPickerViewDelegate, UIPickerViewDataSource>
@property (nonatomic, strong) UILabel *pickerViewLabel;
@property (nonatomic, strong) UIView *pickerViewLabelView;
@property (nonatomic, strong) UIView *pickerContainerView;
@property (nonatomic, strong) UIView *pickerViewContainerView;
@property (nonatomic, strong) UIView *pickerTopBarView;
@property (nonatomic, strong) UIImageView *pickerTopBarImageView;
@property (nonatomic, strong) UIToolbar *pickerViewToolBar;
@property (nonatomic, strong) UIBarButtonItem *pickerViewBarButtonItem;
@property (nonatomic, strong) UIButton *pickerDoneButton;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) NSArray *pickerViewArray;
@property (nonatomic, strong) UIColor *pickerViewTextColor;
@property (nonatomic, strong) UIFont *pickerViewFont;
@property (nonatomic, assign) CGFloat yValueFromTop;
@property (nonatomic, assign) NSInteger pickerViewTextAlignment;
@property (nonatomic, assign) BOOL pickerViewShowsSelectionIndicator;
@property (copy) void (^onDismissCompletion)(NSArray *);
@property (nonatomic, strong) NSArray *timeArray;
@property (nonatomic, strong) NSMutableArray *selectArray;

@end
@implementation MultiSelectPicker

#pragma mark - Singleton
+ (MultiSelectPicker*)sharedView {
    static dispatch_once_t once;
    static MultiSelectPicker *sharedView;
    dispatch_once(&once, ^ { sharedView = [[self alloc] init]; });
    return sharedView;
}

#pragma mark - Show Methods
//显示字符串数组用
+(void)showPickerViewInView:(UIView *)view
                withStrings:(NSArray *)strings
                withOptions:(NSDictionary *)options
                 completion:(void (^)(NSArray *))completion{

    [[self sharedView] initializePickerViewInView:view
                                        withArray:strings
                                      withOptions:options];
    
    [[self sharedView] setPickerHidden:NO callBack:nil];
    [self sharedView].onDismissCompletion = completion;
    [view addSubview:[self sharedView]];
    
}

#pragma mark - Dismiss Methods

+(void)dismissWithCompletion:(void (^)(NSArray *))completion{
    [[self sharedView] setPickerHidden:YES callBack:completion];
}

-(void)dismiss{
    [MultiSelectPicker dismissWithCompletion:self.onDismissCompletion];
}

+(void)removePickerView{
    [[self sharedView] removeFromSuperview];
}

#pragma mark - Show/hide PickerView methods

-(void)setPickerHidden: (BOOL)hidden
              callBack: (void(^)(NSArray *))callBack; {
    
    [UIView animateWithDuration:0.3
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         
                         if (hidden) {
                             [_pickerViewContainerView setAlpha:0.0];
                             [_pickerContainerView setTransform:CGAffineTransformMakeTranslation(0.0, CGRectGetHeight(_pickerContainerView.frame))];
                         } else {
                             [_pickerViewContainerView setAlpha:1.0];
                             [_pickerContainerView setTransform:CGAffineTransformIdentity];
                         }
                     } completion:^(BOOL completed) {
                         if(completed && hidden){
                             [MultiSelectPicker removePickerView];
                             callBack([self selectedObject]);
                         }
                     }];
    
}

-(void)layoutSubviews
{

}

#pragma mark - UIPickerViewDelegate

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if(component == 0) {
        _selectArray[0]= _pickerViewArray[row];
        self.onDismissCompletion (_selectArray);

    } else {
        _selectArray[1]= _timeArray[row];
        self.onDismissCompletion (_selectArray);
    }
    
}

- (id)selectedObject {
    
    NSString *string1 = _pickerViewArray[[self.pickerView selectedRowInComponent:0]];
    NSString *string2 = _timeArray[[self.pickerView selectedRowInComponent:1]];
    
    NSArray *array = @[string1,string2];
    return array;
}

#pragma mark - Initialize PickerView

-(void)initializePickerViewInView: (UIView *)view
                        withArray: (NSArray *)array
                      withOptions: (NSDictionary *)options {
    
    NSMutableArray *selectArray = [NSMutableArray arrayWithObjects:@"Today",@"08:00-8:25", nil];
    _selectArray = selectArray;
    _pickerViewArray = array;
    
    id chosenObject = options[PTselectedObject];
    NSInteger selectedRow;
    
    if (chosenObject!=nil) {
        selectedRow = [_pickerViewArray indexOfObject:chosenObject];
    }else{
        selectedRow = [[_pickerViewArray objectAtIndex:0] integerValue];
    }
    
    
    NSNumber *textAlignment = [[NSNumber alloc] init];
    textAlignment = options[PTtextAlignment];
    //Default value is NSTextAlignmentCenter
    _pickerViewTextAlignment = 1;
    
    if (textAlignment != nil) {
        _pickerViewTextAlignment = [options[PTtextAlignment] integerValue];
    }
    
    BOOL showSelectionIndicator = [options[PTshowsSelectionIndicator] boolValue];
    
    if (!showSelectionIndicator) {
        _pickerViewShowsSelectionIndicator = 1;
    }
    _pickerViewShowsSelectionIndicator = showSelectionIndicator;
    
    UIColor *pickerViewBackgroundColor = [[UIColor alloc] initWithCGColor:[options[PTbackgroundColor] CGColor]];
    UIColor *pickerViewTextColor = [[UIColor alloc] initWithCGColor:[options[PTtextColor] CGColor]];
    UIColor *toolbarBackgroundColor = [[UIColor alloc] initWithCGColor:[options[PTtoolbarColor] CGColor]];
    UIColor *buttonTextColor = [[UIColor alloc] initWithCGColor:[options[PTbuttonColor] CGColor]];
    UIFont *pickerViewFont = [[UIFont alloc] init];
    pickerViewFont = options[PTfont];
    _yValueFromTop = [options[PTvalueY] floatValue];
    
    [self setFrame: view.bounds];
    [self setBackgroundColor:[UIColor clearColor]];
    
    UIImage * toolbarImage = options[PTtoolbarBackgroundImage];
    
    //Whole screen with PickerView and a diPTed background
    _pickerViewContainerView = [[UIView alloc] initWithFrame:view.bounds];
    [_pickerViewContainerView setBackgroundColor:PTColor(0, 0, 0, 0.2)];
    //  [_pickerViewContainerView setBackgroundColor: [UIColor colorWithRed:0.412 green:0.412 blue:0.412 alpha:0.7]];
    [self addSubview:_pickerViewContainerView];
    
    //PickerView Container with top bar
    _pickerContainerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, _pickerViewContainerView.bounds.size.height - 200.0, _pickerViewContainerView.frame.size.width, 200.0)];
    
    //Default Color Values (if colors == nil)
    
    //PickerViewBackgroundColor - White
    if (pickerViewBackgroundColor==nil) {
        pickerViewBackgroundColor = [UIColor whiteColor];
    }
    
    //PickerViewTextColor - Black
    if (pickerViewTextColor==nil) {
        pickerViewTextColor = [UIColor blackColor];
    }
    _pickerViewTextColor = pickerViewTextColor;
    
    //ToolbarBackgroundColor - Black
    if (toolbarBackgroundColor==nil) {
        toolbarBackgroundColor = [UIColor colorWithRed:0.969 green:0.969 blue:0.969 alpha:0.8];
    }
    
    //ButtonTextColor - Blue
    if (buttonTextColor==nil) {
        buttonTextColor = [UIColor colorWithRed:0.000 green:0.486 blue:0.976 alpha:1];
    }
    
    if (pickerViewFont==nil) {
        _pickerViewFont = [UIFont systemFontOfSize:22];
    }
    _pickerViewFont = pickerViewFont;
    
    
    _pickerContainerView.backgroundColor = pickerViewBackgroundColor;
    [_pickerViewContainerView addSubview:_pickerContainerView];
    
    
    //Content of pickerContainerView
    
    //Top bar view
    _pickerTopBarView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, _pickerContainerView.frame.size.width, 44.0)];
    [_pickerContainerView addSubview:_pickerTopBarView];
    [_pickerTopBarView setBackgroundColor:[UIColor whiteColor]];
    
    
    _pickerViewToolBar = [[UIToolbar alloc] initWithFrame:_pickerTopBarView.frame];
    [_pickerContainerView addSubview:_pickerViewToolBar];
    
    CGFloat iOSVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    //NSLog(@"%f",iOSVersion);
    
    if (iOSVersion < 7.0) {
        _pickerViewToolBar.tintColor = toolbarBackgroundColor;
        //[_pickerViewToolBar setBackgroundColor:toolbarBackgroundColor];
    }else{
        [_pickerViewToolBar setBackgroundColor:toolbarBackgroundColor];
        
        //_pickerViewToolBar.tintColor = toolbarBackgroundColor;
        
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 70000
        _pickerViewToolBar.barTintColor = toolbarBackgroundColor;
#endif
    }
    
    NSArray *timeArray = @[@"08:00-08:25",@"08:30-08:55",@"09:00-9:25",@"09:30-9:55",@"10:00-10:25",@"10:30-10:55",@"11:00-11:25"];
    
    _timeArray = timeArray;
    
    if (toolbarImage!=nil) {
        [_pickerViewToolBar setBackgroundImage:toolbarImage forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    }
    
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIImage *image = [[UIImage imageNamed:@"Button@2x"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _pickerViewBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    [_pickerViewBarButtonItem setImage:image];
    

    
    _pickerViewToolBar.items = @[flexibleSpace, _pickerViewBarButtonItem];
    [_pickerViewBarButtonItem setTintColor:buttonTextColor];
    
    
    //Add pickerView
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0, 34.0, _pickerViewToolBar.frame.size.width, 180)];
    [_pickerView setDelegate:self];
    [_pickerView setDataSource:self];
    [_pickerView setShowsSelectionIndicator: _pickerViewShowsSelectionIndicator];//YES];
    [_pickerContainerView addSubview:_pickerView];
    
    //[self.pickerViewContainerView setAlpha:0.0];
    [_pickerContainerView setTransform:CGAffineTransformMakeTranslation(0.0, CGRectGetHeight(_pickerContainerView.frame))];
    
    //Set selected row
    [_pickerView selectRow:selectedRow inComponent:0 animated:YES];
    [_pickerView selectRow:selectedRow inComponent:1 animated:YES];

    
    
}
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 36.0;
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView: (UIPickerView *)pickerView {
    return 2;

}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component {
    if(component == 0) {
        
        return [_pickerViewArray count];

    } else {
        return [_timeArray count];

    }
}




- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row
          forComponent:(NSInteger)component
           reusingView:(UIView *)view {
    
    UIView *customPickerView = view;
    
    UILabel *pickerViewLabel;
    
    if (customPickerView==nil) {
        
        CGRect frame = CGRectMake(0.0, 0.0, 126.0, 35.0);
        customPickerView = [[UIView alloc] initWithFrame: frame];
        [customPickerView setBackgroundColor:[UIColor whiteColor]];

        if (_yValueFromTop == 0.0f) {
            _yValueFromTop = 3.0;
        }


        CGRect labelFrame = CGRectMake(0.0, _yValueFromTop, 126.0, 35); // 35 or 44
        pickerViewLabel = [[UILabel alloc] initWithFrame:labelFrame];
        [pickerViewLabel setTag:1];
        [pickerViewLabel setTextAlignment: _pickerViewTextAlignment];
        [pickerViewLabel setBackgroundColor:[UIColor whiteColor]];
        [pickerViewLabel setTextColor:_pickerViewTextColor];
        [pickerViewLabel setFont:_pickerViewFont];
        [customPickerView addSubview:pickerViewLabel];
    } else{
        
        for (UIView *view in customPickerView.subviews) {
            if (view.tag == 1) {
                pickerViewLabel = (UILabel *)view;
                break;
            }
        }
    }

    
    if(component == 0) {
            [pickerViewLabel setText: [_pickerViewArray objectAtIndex:row]];
    } else {
            [pickerViewLabel setText: [_timeArray objectAtIndex:row]];
        
    }
    return customPickerView;
    
}


@end
